#include "qAnalitikaArtikliwidget.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDesktopWidget>
#include "chelperclass.h"

QAnalitikaArtikliWidget::QAnalitikaArtikliWidget(QWidget *parent)
	: QMyBaseFormWidget(parent)
    ,m_selectedText("") 
    ,m_selectedTextName("")
	,m_offset(0)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView->setSortingEnabled(true);
	connect(ui.prevButton, SIGNAL(clicked()), this, SLOT(prevButtonPressed()));
	connect(ui.nextButton, SIGNAL(clicked()), this, SLOT(nextButtonPressed()));
    
    connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
    lista("%");
    lista_detail("-1");
}

QAnalitikaArtikliWidget::~QAnalitikaArtikliWidget()
{

}


void QAnalitikaArtikliWidget::pressEscape()
{
    emit closeW();
}

void QAnalitikaArtikliWidget::prevButtonPressed()
{
	m_offset = m_offset <= 50 ? 0 : m_offset - 50;
	lista("%%%");
}


void QAnalitikaArtikliWidget::nextButtonPressed()
{
	m_offset += 50;
	lista("%%%");
}

void QAnalitikaArtikliWidget::lista(const QString& nameSearch)
{
    QLocale loc;
    int r = 0;
    int c = 4;
    int fieldNo[4];
    QString country[4];
    int colWidth[] = {50, 250, 80, 200};
    QString colName[7] = {"id", "artikal", "edm", "proizvoditel"};
    QString temp = "";

    bool isNumeric = false;

    temp =
        "select distinct magacin.artikal_id ,artikli.artikal, artikli.edm, artikli.proizvoditel "
		" FROM dokumenti "  
		" LEFT JOIN magacin ON dokumenti.dok_id = magacin.dok_id  and dokumenti.dok_tip_link = magacin.dok_tip_link "  
        " left join artikli on  magacin.artikal_id = artikli.id "
		" where artikli.artikal like '%" + nameSearch + 
        "%' order by artikal_id limit 50 OFFSET "+ QString::number(m_offset, 10);

    QSqlQuery query(temp);
    QSqlError err = query.lastError();
    model = new QStandardItemModel(r, c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Артикал Ид."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Едм"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Производител"));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);

    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
	CHelperClass chc(this);
	float vkVlezKol = 0.f;
	float vkIzlezKol = 0.f;
	float vkSaldo = 0.f;
	setUpdatesEnabled(false);
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QString temp = query.value(i).toString();
            QStandardItem *item = NULL; 
            item = new QStandardItem(temp);
            item->setTextAlignment(Qt::AlignLeft);
            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
			
			model->setItem(row, i, item);
        }
        row++;
    } 
	setUpdatesEnabled(true);

    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
}

void QAnalitikaArtikliWidget::on_lineEdit_textChanged(const QString &)
{
	lista(ui.lineEdit->text());
}


void QAnalitikaArtikliWidget::on_tableView_clicked(const QModelIndex &modelX)
{
	int i = modelX.row();
	m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
}

void QAnalitikaArtikliWidget::setFocusSearchField()
{
	ui.lineEdit->setFocus();
}


void QAnalitikaArtikliWidget::pressReturn()
{
    if (ui.lineEdit->hasFocus())
    {
        ui.tableView->setFocus();
    }
    else if (ui.tableView->hasFocus())
	{
		emit sAnalitikaArtikliToDokument(m_selectedText, m_selectedTextName, m_selectedTextNameSaldo);	
	}

}

void QAnalitikaArtikliWidget::setInitText(QString text)
{
	ui.lineEdit->setText(text);
	ui.lineEdit->selectAll();
	ui.lineEdit->setFocus();
}

void QAnalitikaArtikliWidget::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    m_selectedText = model->item(i, 0) ? model->item(i, 0)->text():"";
    m_selectedTextName = model->item(i, 1) ? model->item(i, 1)->text():"";
    m_selectedTextName2 = model->item(i, 2) ? model->item(i, 2)->text():"";

    m_selectedTextNameSaldo = model->item(i, 5) ? model->item(i, 5)->text():"";
    lista_detail(m_selectedText);
}

void QAnalitikaArtikliWidget::lista_detail(const QString& nameSearch)
{
    QLocale loc;

    int r = 0;
    int c = 7;
    int fieldNo[7];
    int colWidth[] = {100, 80, 100, 200, 80, 80, 80};
    QString temp = "";
    temp = 
		" SELECT datum, dokumenti.dok_id, datum, naziv, magacin.dok_tip, ikol "  
		" FROM dokumenti "  
		" LEFT JOIN magacin ON dokumenti.dok_id = magacin.dok_id  and dokumenti.dok_tip_link = magacin.dok_tip_link "  
		" LEFT JOIN komintenti ON dokumenti.komintent_id = komintenti.id "  
		" WHERE magacin.artikal_id = "+ nameSearch +" ORDER BY datum, dokumenti.id ";
    QSqlQuery query(temp);
    model2 = new QStandardItemModel(r,c);
    model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Датум на книжење"));
    model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Док.Ид."));
    model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Датум на документ"));
    model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Назив на док"));
    model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Влез"));
    model2->setHeaderData( 5, Qt::Horizontal, trUtf8("Излез"));
    model2->setHeaderData( 6, Qt::Horizontal, trUtf8("Состојба"));
    ui.tableView_2->setModel(model2);
    header2 = new QHeaderView(Qt::Horizontal, this);
    header2->setClickable(true);
    ui.tableView_2->setHorizontalHeader(header2);
    header2->show();
    int row = 0;
    float saldo = 0.f;
	int stop = 0;
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QStandardItem *item = NULL;
            QString temp = query.value(i).toString();
			
			if (i == 1)
			{
				int tipTemp = query.value(4).toInt();
				switch(tipTemp)
				{
				case 20 : temp = trUtf8("ПРИЕМ. - ") + temp; break;
				case 22 : temp = trUtf8("НАЛОГ  - ") + temp; break;
				case 23 : temp = trUtf8("ПОВР.  - ") + temp;
					 stop = 0;
					break;
				case 24 : temp = trUtf8("ПРИЕМ. - ") + temp; break;
				case 40 : temp = trUtf8("ИСПРА. - ") + temp; break;
				case 41 : temp = trUtf8("НАЛОГ  - ") + temp; break;
				case 44 : temp = trUtf8("ИСПРА. - ") + temp; break;
				case 80 : temp = trUtf8("НАРАЧ. - ") + temp; break;
				case 18 : temp = trUtf8("НАРАЧ. - ") + temp; break;
				}
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);

			}
			else if ((i == 0)||(i == 2)) 
			{
				temp = temp.left(10);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}

			else if (i == 4) // vnes
			{
				QString temp = query.value(5).toString();
				if ((query.value(4).toString() == "20")||
					(query.value(4).toString() == "22")||
					(query.value(4).toString() == "23")||
					(query.value(4).toString() == "24"))
				{
					saldo += temp.toFloat();
					temp =  loc.toString(temp.toFloat(), 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				else
				{
					temp = "0";
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
			}
			else if (i == 5)
			{
				QString temp = query.value(5).toString();
				if ((query.value(4).toString() == "40")||
					(query.value(4).toString() == "41")||
					(query.value(4).toString() == "44"))
				{
					saldo -= temp.toFloat();
					temp =  loc.toString(temp.toFloat(), 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				else
				{
					temp = "0";
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
			}
			else if (i == 6)
			{
				temp =  loc.toString(saldo, 'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else
			{
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}
			item->setEditable(false);
			ui.tableView_2->setRowHeight(row, 18);
			ui.tableView_2->setColumnWidth(i, colWidth[i]);
			model2->setItem(row, i, item);
        }
		row++;
    } 
    ui.tableView_2->show();
}

void QAnalitikaArtikliWidget::radioButtonClicked()
{
    lista(ui.lineEdit->text());
}